package com.pocketsweet.ui.fragments;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.lidroid.xutils.ViewUtils;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.R;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.LoginService;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.Profile;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.MixListView;
import com.pocketsweet.ui.uilib.SlideView;
import com.pocketsweet.ui.uilib.SlideView.OnSlideListener;
import com.pocketsweet.ui.uilib.adapter.OnLineListAdapter;
import com.pocketsweet.ui.uilib.adapter.OnLineListAdapter.ViewHolder;
import com.pocketsweet.utils.ToolKits;

public class NewOnlineFragment extends Fragment implements OnRefreshListener,
        OnLoadListener, OnItemClickListener {

    public static MixListView dropDownListView = null;
    private static OnLineListAdapter onLineListAdapter;
    public static List<MLUser> userList = new ArrayList<MLUser>();
    public static final int MORE_DATA_MAX_COUNT = 30; // 每页20个对象
    public static final int BEGIN_TO_LOADING = -1;
    public int skipDataCount = 0; // 忽略前N个对象
    private boolean isUpdateList = false; // 是否刷新列表
    private MLApplication mlApplication;
    private LinearLayout linBlank;
    public static boolean isSlide = false;
    final int RIGHT = 0;
    final int LEFT = 1;

    private boolean isClicked = false;

    public MLUser mlUser;
    public ViewHolder userHolder;
    public static OnSlideListener slideLister;
    private SlideView mLastSlideViewWithStatusOn;
    private LoginService loginService;

    private LinearLayout llRandomCall;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Main.ACTION_CHOOSE_CHANGE)) {
                if (Main.choosedSex == 0) {
                    Main.getInstance().getHeader()
                            .setRightImg(R.drawable.icon_sex_all);
                } else if (Main.choosedSex == 1) {
                    Main.getInstance().getHeader()
                            .setRightImg(R.drawable.icon_sex_man);
                } else if (Main.choosedSex == 2) {
                    Main.getInstance().getHeader()
                            .setRightImg(R.drawable.icon_sex_female);
                }
                if (userList != null) {
                    userList.clear();
                }
                onLineListAdapter.notifyDataSetChanged();
                dropDownListView.setAdapter(onLineListAdapter);
                getUserList(BEGIN_TO_LOADING);
            }
            if (intent.getAction().equals(Main.ACTION_LIKE_POEPLE_REFRESH)) {
                onLineListAdapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_newonline, null);
        mlApplication = (MLApplication) getActivity().getApplication()
                .getApplicationContext();
        ViewUtils.inject(this, rootView);
        // initListview();
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dropDownListView = (MixListView) getView().findViewById(
                R.id.dropDownListview);
        linBlank = (LinearLayout) getView().findViewById(R.id.linBlank);
        loginService = new LoginService(getActivity());
        onLineListAdapter = new OnLineListAdapter(getActivity(), userList);
        dropDownListView.setAdapter(onLineListAdapter);
        onLineListAdapter.notifyDataSetChanged();
        dropDownListView.setPageSize(MORE_DATA_MAX_COUNT);
        dropDownListView.setOnRefreshListener(this);
        dropDownListView.setOnLoadListener(this);
        dropDownListView.setOnItemClickListener(this);
        getUserList(BEGIN_TO_LOADING);// 首次进入app，加载数据
        // MLContext.deleteAll(); // 清空sharepreference
        slideLister = new OnSlideListener() { // 如果当前存在已经打开的SlideView，那么将其关闭

            @Override
            public void onSlide(View view, int status) {
                if (mLastSlideViewWithStatusOn != null
                        && mLastSlideViewWithStatusOn != view) {
                    mLastSlideViewWithStatusOn.shrink();
                }

                if (status == SLIDE_STATUS_ON) {
                    mLastSlideViewWithStatusOn = (SlideView) view;
                }

            }
        };

        // 情侣电话
        // llRandomCall = (LinearLayout)
        // getView().findViewById(R.id.llRandomCall);
        // llRandomCall.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // if (isClicked == true) {
        // return;
        // }
        // isClicked = true;
        // Intent intent = new Intent(getActivity(),
        // RandomCallMatchingActivity.class);
        // getActivity().startActivity(intent);
        // }
        // });
    }

    @Override
    public void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Main.ACTION_CHOOSE_CHANGE);
        filter.addAction(Main.ACTION_LIKE_POEPLE_REFRESH);
        getActivity().registerReceiver(receiver, filter);
    }

    @Override
    public void onResume() {
        isClicked = false;
        super.onResume();
        if (Main.needRefresh) {
            getUserList(AutoListView.REFRESH);
        }
        if (userHolder != null) {
            userHolder.update(mlUser);
            userHolder = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }

    /*
     * 请求最近在线对象
     */
    private void getUserList(final int what) {
        userList = mlApplication.getUserList(); // 从Application里获取userList，若为空则获取网络数据
        if (what != BEGIN_TO_LOADING) {
            isUpdateList = true; // 如果不是首次加载数据，则该动作为刷新

        } else {
            dropDownListView.setRefreshData(); // 初始化显示loading动态图片
        }
        if (userList == null || userList.size() <= 0 || isUpdateList) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud
            AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
            skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
            if (what != AutoListView.LOAD) {
                skipDataCount = 0; // 刷新时不用忽略前面对象
                AVAnalytics.onEvent(getActivity(), "空闲恋人刷新");//埋点
            }
            // if (Main.choosedCity == 1
            // && UserService.getCurrentUser().getLocationCity() != null) {
            // query.whereEqualTo(MLUser.LOCATION_CITY, UserService
            // .getCurrentUser().getLocationCity());//同城筛选
            //
            // }
            if (Main.choosedSex != 0) {
                if (Main.choosedSex == 1) { // 若选择男性
                    query.whereEqualTo(MLUser.GENDER, 1);
                } else if (Main.choosedSex == 2) {
                    query.whereEqualTo(MLUser.GENDER, 2);

                }

            }
            // if (Main.choosedType == C.USER_TYPE_RECOMMENDED) {//筛选是否为编辑推荐
            query.whereNotEqualTo(MLUser.TYPE, C.USER_TYPE_NORMAL);
            // }
            query.whereNotEqualTo(MLUser.STATUS, C.USER_STATUS_DISABLE);
            query.whereNotEqualTo(MLUser.STATUS, C.USER_STATUS_BADINFO);

            linBlank.setVisibility(View.GONE);
            query.setSkip(skipDataCount); // 忽略前N个
            query.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
            query.orderByDescending(MLUser.LASTLOGIN);
            query.whereEqualTo("isUserInited", 1); // 只显示 认证完成的用户
            // query.whereNotEqualTo("objectId", UserService.getCurrentUser()
            // .getObjectId());// 不用显示自己
            query.findInBackground(new FindCallback<MLUser>() {
                @Override
                public void done(List<MLUser> users, AVException e) {
                    // loading.dismiss();
                    // 取出参与的人
                    // Log.e("==user==", users.toString() + " ");
                    if (e == null) {

                        if (users.size() != 0) {
                            switch (what) {
                                case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
                                    userList = users;
                                    dropDownListView.onRefreshComplete();
                                    // onLineListAdapter.setDatas(userList);
                                    loginService.setLastLoginDate();
                                    break;
                                case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
                                    dropDownListView.onLoadComplete();
                                    userList.addAll(users);
                                    break;
                                case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
                                    userList = users;
                                    dropDownListView.onRefreshComplete();
                                    loginService.setLastLoginDate();
                                    // onLineListAdapter.setDatas(userList);
                                    break;
                            }
                            linBlank.setVisibility(View.GONE);
                            mlApplication.setUserList(userList);
                            dropDownListView.setResultSize(userList.size());
                            onLineListAdapter.setDatas(userList);
                            onLineListAdapter.notifyDataSetChanged();
                            isUpdateList = false; // 刷新完毕，设为false
                        } else if (users.size() == 0) {
                            if (what != AutoListView.LOAD) {
                                ToolKits.toast(getActivity(), "无搜索结果");
                            }
                            dropDownListView.setNoData();
                        }
                    } else {
                        // error ，继续重新获取
                        // Log.e("==nothing", "error:" + e.getMessage());
                        linBlank.setVisibility(View.VISIBLE);
                        getUserList(BEGIN_TO_LOADING);
                    }
                }
            });
        } else {
            // Log.e("==refresh", "begin to load false ");
        }
    }

    @Override
    public void onLoad() {
        getUserList(AutoListView.LOAD);
    }

    @Override
    public void onRefresh() {
        getUserList(AutoListView.REFRESH);
        dropDownListView.setOnRefreshListener(this);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // if (position == 1) {
        //
        // if (isClicked == false) {
        // isClicked = true;
        // Intent intent = new Intent(getActivity(),
        // RandomCallMatchingActivity.class);
        // getActivity().startActivity(intent);
        // String sex = null;
        // if (UserService.getCurrentUser().getType() == 1) {
        // sex = "男";
        // } else {
        // sex = "女";
        // }
        //
        // }
        // } else {
        // mlUser = (MLUser) onLineListAdapter.getItem(position - 2);
        if (position - 1 < 0 || onLineListAdapter.getCount() <= 0) {
            return;
        }
        mlUser = (MLUser) onLineListAdapter.getItem(position - 1);
        // Log.e("=isSlide=", "isSlide:" + String.valueOf(isSlide));
        if (mlUser.getType() == C.USER_TYPE_NORMAL) {
            isSlide = false;
        }
        if (isSlide == true && mlUser.slide.isScroll == true) { // 如果正在滑动，不触发点击事件
            return;
        }
        userHolder = onLineListAdapter.new ViewHolder(view);

        String selectedUserId = ((MLUser) onLineListAdapter
                .getItem(position - 1)).getObjectId();
        // String selectedUserId = ((MLUser) onLineListAdapter
        // .getItem(position - 2)).getObjectId();
        // String likeCount = ((TextView) view.findViewById(R.id.tvLike))
        // .getText().toString();
        // boolean isLiked = MLContext.getUserLikeID(selectedUserId) == 0 ?
        // false
        // : true;
        Intent intent;
        intent = new Intent(getActivity(), Profile.class);
        // Log.e("String", selectedUserId + "  " + likeCount);
        intent.putExtra("userId", selectedUserId);
        intent.putExtra("nickname", mlUser.getNickname());
        // intent.putExtra("position", String.valueOf(position - 2));
        getActivity().startActivity(intent);

        // }

    }
}